package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 查询区间内营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateTimeList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateTimeList.add(begin);
            begin = begin.plusDays(1);
        }
        dateTimeList.add(end);
        String dateTime = StringUtils.join(dateTimeList, ",");

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateTimeList) {
            // 查询date日期状态为已完成的订单金额总和
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        }

        String turnover = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO.builder().dateList(dateTime).turnoverList(turnover).build();
    }

    /**
     * 查询区间内用户统计数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateTimeList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateTimeList.add(begin);
            begin = begin.plusDays(1);
        }
        dateTimeList.add(end);
        String dateTime = StringUtils.join(dateTimeList, ",");

        List<Integer> newUerlist = new ArrayList<>();
        List<Integer> totalUerlist = new ArrayList<>();


        for (LocalDate localDate : dateTimeList) {
            // 查询date日期状态为已完成的订单金额总和
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            totalUerlist.add(userMapper.countByMap(map));
            map.put("begin", beginTime);
            newUerlist.add(userMapper.countByMap(map));
        }
        String totalUserString = StringUtils.join(totalUerlist, ",");
        String newUserString = StringUtils.join(newUerlist, ",");


        return UserReportVO
                .builder()
                .dateList(dateTime)
                .totalUserList(totalUserString)
                .newUserList(newUserString)
                .build();
    }

    /**
     * 查询区间内订单统计数据
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateTimeList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateTimeList.add(begin);
            begin = begin.plusDays(1);
        }
        dateTimeList.add(end);
        String dateTime = StringUtils.join(dateTimeList, ",");

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validorderCountList = new ArrayList<>();

        for (LocalDate localDate : dateTimeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            orderCountList.add(orderMapper.countByMap(map));
            map.put("status", Orders.COMPLETED);
            validorderCountList.add(orderMapper.countByMap(map));
        }

        String orderCountString = StringUtils.join(orderCountList, ",");
        String validorderCountString = StringUtils.join(validorderCountList, ",");

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validtotalOrderCount = validorderCountList.stream().reduce(Integer::sum).get();

        Double validRate = totalOrderCount == 0 ? 0 : validtotalOrderCount * 1.0 / totalOrderCount;

        return OrderReportVO
                .builder()
                .dateList(dateTime)
                .orderCountList(orderCountString)
                .validOrderCountList(validorderCountString)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validtotalOrderCount)
                .orderCompletionRate(validRate)
                .build();
    }

    /**
     * Top10菜品套餐统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop(beginTime, endTime);

        List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameString = StringUtils.join(names, ",");
        String numberString = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameString)
                .numberList(numberString)
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    @Override
    public void exportBussinessData(HttpServletResponse response) {
        // 查询数据库（最近30天）
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));


        // 将查询到的数据写入xlxs
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 填充数据
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 时间
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + "到" + end);
            // 概览数据
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细数据
            int row_index = 7;
            for (int i = 0; i < 30; i++) {
                LocalDate day = begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(day, LocalTime.MIN), LocalDateTime.of(day, LocalTime.MAX));
                sheet1.getRow(row_index + i).getCell(1).setCellValue(day.toString());
                sheet1.getRow(row_index + i).getCell(2).setCellValue(businessData.getTurnover());
                sheet1.getRow(row_index + i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet1.getRow(row_index + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet1.getRow(row_index + i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet1.getRow(row_index + i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 通过输出流保存文件
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            // 关闭资源
            outputStream.close();
            excel.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
